﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace KouDai.Core.Engine
{
    public class HttpEngine
    {
        #region Fields
        private object operateLock = new object();
        #endregion

        #region Method
        public async Task<byte[]> Request(string url, string method, string data, CancellationToken cancellationToken)
        {
            WebResponse response;
            //创建request
            HttpWebRequest httpWebRequest = WebRequest.CreateHttp(url);

            if (method.Equals("POST", StringComparison.CurrentCultureIgnoreCase))
            {
                httpWebRequest.Headers["encryType"] = "3";
                httpWebRequest.Headers["gzipType"] = "0";
                httpWebRequest.Headers["Accept-Encoding"] = "geili-zip";
                httpWebRequest.Headers["Content-Encoding"] = "geili-zip";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

                using (Stream stream = await httpWebRequest.GetRequestStreamAsync())
                {
                    byte[] content = Encoding.UTF8.GetBytes(data);
                    stream.Write(content, 0, content.Length);
                }
                response = await httpWebRequest.GetResponseAsync().WithCancellation<WebResponse>(cancellationToken);
            }
            else if ("GET".Equals(method, StringComparison.CurrentCultureIgnoreCase))
            {
                response = await httpWebRequest.GetResponseAsync();
            }
            else
            {
                throw new ArgumentException("method can't be null");
            }
            using (Stream responseStream = response.GetResponseStream())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] buffer = new byte[8 * 1024];
                    int read = 0;
                    while ((read = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    return ms.ToArray();
                }
            }
        }
        #endregion
        
    }
}
